package com.wzcl.app.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wzcl.app.controller.student.IosPayController;
import com.wzcl.app.dao.model.RechargePriceList;
import com.wzcl.app.dao.model.TopUpOrder;
import com.wzcl.app.dao.model.Orders;
import com.wzcl.app.dao.repository.OrdersRepository;
import com.wzcl.app.dao.repository.RechargePriceListRepository;
import com.wzcl.app.dao.repository.TopUpOrderRepository;
import com.wzcl.app.dao.repository.UserTopUpRepository;
import com.wzcl.app.model.common.RVO;
import com.wzcl.app.model.dto.IosPayDto;
import com.wzcl.app.service.IosPayService;
import com.wzcl.app.service.UserTopUpService;
import com.wzcl.app.utils.DateUtil;
import com.wzcl.app.utils.IosVerifyUtil;
import com.wzcl.app.utils.OrderNoUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author beingven
 * @Description 苹果内购支付
 * @createTime 2020年11月17日 15:33:00
 */
@Service
public class IosPayServiceImpl implements IosPayService {
    private static final Logger log = LoggerFactory.getLogger(IosPayController.class);

    @Resource
    private UserTopUpService userTopUpService;
    @Resource
    private TopUpOrderRepository topUpOrderRepository;
    @Resource
    private RechargePriceListRepository rechargePriceListRepository;

    /**
     * 发起IOS内购支付
     * @param iosPayDto 包含receipt校验体和订单号的Dto
     * @return 返回包含支付状态的RVO
     */
    @Override
    public RVO createIosPay(IosPayDto iosPayDto) {
        //校验用户是否登录
        //线上环境验证
        String verifyResult = IosVerifyUtil.buyAppVerify(iosPayDto.getTransactionReceipt(), 0);
        if (verifyResult == null) {
            return RVO.error("苹果验证失败，返回数据为空");
        } else {
            JSONObject appleReturn = JSONObject.parseObject(verifyResult);
            String states = appleReturn.getString("status");
            //无数据则沙箱环境验证
            if ("21007".equals(states)) {
                verifyResult = IosVerifyUtil.buyAppVerify(iosPayDto.getTransactionReceipt(), 0);
                appleReturn = JSONObject.parseObject(verifyResult);
                states = appleReturn.getString("status");
            }
            // 前端所提供的收据是有效的验证成功
            if ("0".equals(states)) {
                //支付成功修改订单状态
                log.info("---------------订单开始更新---------------");
                log.info("订单号："+iosPayDto.getOrderNo());
                topUpOrderRepository.updatePayStateByOrderNumber(1, 1, iosPayDto.getOrderNo());
                // 充值学币
                //获取订单充值信息并充值
                log.info("---------------苹果支付收据验证成功开始充值---------------");
                RVO rvo = userTopUpService.userTopUp(iosPayDto.getProductId());
                if (rvo.getCode() == 200){
                    log.info("---------------充值成功---------------");
                    return RVO.success("充值成功");
                }
                return RVO.error("充值学币异常");
            } else {
                return RVO.error("支付失败，错误码：" + states);
            }
        }
    }

    /**
     * 创建订单
     * @param productId 充值的产品id
     * @return 返回订单信息
     */
    @Override
    public RVO save(String productId) throws Exception {
        log.info("---------------开始创建苹果支付订单---------------");
        TopUpOrder topUpOrder = new TopUpOrder();
        //获取用户电话号码
        String phone = SecurityContextHolder.getContext().getAuthentication().getName();
        //订单号生成
        String orderNumber = OrderNoUtil.generateOrderNo(phone).toString();
        topUpOrder.setUserPhone(phone);
        //获取订单创建时间
        long time = System.currentTimeMillis();
        topUpOrder.setCreateTime(DateUtil.getDateBySystemTime(time));
        topUpOrder.setUpdateTime(DateUtil.getDateBySystemTime(time));
        // 订单金额
        topUpOrder.setMoney(rechargePriceListRepository.findAllByProductId(productId).getMoney());
        // 订单创建
        topUpOrder.setOrderState(0);
        // 未支付
        topUpOrder.setPayState(0);
        topUpOrder.setOrderNumber(orderNumber);
        TopUpOrder save = topUpOrderRepository.save(topUpOrder);
        return RVO.success(save);
    }
}